/*
 * @lc app=leetcode.cn id=160 lang=typescript
 *
 * [160] 相交链表
 */

// @lc code=start
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     val: number
 *     next: ListNode | null
 *     constructor(val?: number, next?: ListNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.next = (next===undefined ? null : next)
 *     }
 * }
 */
function nodeEquals(headA: ListNode | null, headB: ListNode | null): boolean {
    while (headA && headB) {
        if (headA.val != headB.val) { return false }
        headA = headA.next;
        headB = headB.next
    }
    return true
}
function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): ListNode | null {

    if (headA == null || headB == null) return null;
    let pA = headA, pB = headB;
    while (pA != pB) {
        pA = pA == null ? headB : pA.next;
        pB = pB == null ? headA : pB.next;
    }
    return pA;




    let a = headA;
    let b = headB;
    if (!a || !b) { return null }
    while (a) {
        while (b) {
            if(nodeEquals(a,b)){
                return a
            }
            // if (a.val == b.val) {
            //     let aa = a;
            //     let bb = b;
            //     let f = true
            //     while (aa && bb) {
            //         if (aa.val != bb.val) {
            //             f = false
            //         }
            //         aa = aa.next;
            //         bb = bb.next
            //     }
            //     if (f) {
            //         return aa
            //     }
            // }
            b = b.next
        }
        a = a.next
        b = headB;
    }
    return null
};
// @lc code=end

